package com.shzq.service.impl;

import com.alibaba.fastjson.JSON;
import com.shzq.dao.PointMapper;
import com.shzq.pojo.Node;
import com.shzq.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RedisServiceImpl implements RedisService {

    public static final String POINT_MAP = "point_map";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PointMapper pointMapper;

    @Override
    public void importData() {
        Set<Node> geoSet  = getAllPointMap();
        HashMap<String, Point> points= new HashMap<>();
        geoSet.forEach(node -> points.put(node.getKey(),node.getPoint()));
        redisTemplate.boundGeoOps("latitude").add(points);
    }

    private Map<String, Node> createPointMap(){
        Set<Node> geoSet  = getAllPointMap();
        HashMap<String, Node> points= new HashMap<>();
        geoSet.forEach(node -> points.put(node.getKey(),node));
        return points;
    }
    @Override
    public Map<String, Node> getPointMap() {
        return createPointMap();
    }

    @Override
    public Set<Node> getAllPointMap(){
        List<Map<String,String>> allLatitude = pointMapper.findAllLatitude();
        Set<Node> geoSet = new HashSet<>();
        allLatitude.forEach(map->{
            String[] split = map.get("latitude") .split(":");
            if (split[0].length()>6) split[0] = split[0].substring(0, 5);
            if(split[1].length()>6)split[1] = split[1].substring(0,5);
            Point point = new Point(Double.parseDouble(split[0]), Double.parseDouble(split[1]));
            String id = String.valueOf(map.get("id"));
            String name = "id_"+id;
            geoSet.add(new Node(name,point,null));
        });
        return geoSet;
    }
}